<template>
  <div
    style="display: flex; flex-direction: row; margin-top: 10px"
    process-status="success"
    align-center
  >
    <el-steps
      :space="200"
      :active="stepActive"
      simple
      style="width: 58%; height: 9px; margin-left: 10px"
    >
      <el-step title="基础信息" :icon="Edit" />
      <el-step title="详细配置" :icon="UploadFilled" />
      <el-step title="完成" :icon="Picture" />
    </el-steps>
    <div style="margin-left: 50px">
      <el-button
        type="info"
        :disabled="stepActive <= 1"
        @click="stepActive = stepActive - 1"
        >上一步</el-button
      >
      <el-button
        type="primary"
        :disabled="stepActive >= 3"
        @click="goOnContinue(ruleFormRef)"
        >继续</el-button
      >
      <el-button type="danger" @click="emit('closed')">关闭</el-button>
    </div>
  </div>
  <div v-if="stepActive === 1" v-loading="fullscreenLoading">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      label-width="auto"
      label-position="top"
      size="10"
      :rules="rules"
      style="margin-top: 20px; margin-left: 10px; margin-right: 10px"
    >
      <el-row gutter="20">
        <el-col :span="8">
          <el-form-item label="选择表" prop="dbTable">
            <el-select
              v-model="tableData"
              remote
              reserve-keyword
              clearable
              placeholder="请选择选择数据库表"
            >
              <el-option
                v-for="item in tableList"
                :key="item.tableName"
                :label="item.tableName + '-' + item.tableRemark"
                :value="item.tableName"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="选择主键" prop="dbTableKey">
            <el-select
              v-model="ruleForm.dbTableKey"
              remote
              reserve-keyword
              clearable
              placeholder="请选择选择数据库表"
            >
              <el-option
                v-if="dbTableKeyList.length > 0"
                v-for="item in dbTableKeyList"
                :key="item.columnName"
                :label="item.columnName + `[${item.columnRemark}]`"
                :value="item.columnName"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="上级目录" prop="menuPid">
            <el-tree-select
              v-model="ruleForm.menuPid"
              :data="menuData"
              check-strictly
              :props="defaultProps"
              node-key="id"
              :render-after-expand="false"
              style="width: 240px"
            >
              <template #default="{ node, data }">
                <span class="custom-tree-node">
                  <span>{{ data.name }}</span>
                </span>
              </template>
            </el-tree-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row gutter="20">
        <el-col :span="8">
          <el-form-item label="生成方式" prop="generateType">
            <el-radio-group v-model="ruleForm.generateType" class="ml-4">
              <el-radio
                v-for="value in generateTypeOptions"
                :label="value.value"
                size="large"
                >{{ value.label }}</el-radio
              >
              <!-- <el-radio label="2" size="large">项目内</el-radio> -->
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="表前缀移除" prop="tablePrefix">
            <el-radio-group v-model="ruleForm.tablePrefix" class="ml-4">
              <el-radio
                v-for="value in tablePrefixOptions"
                :label="value.value"
                size="large"
                >{{ value.label }}</el-radio
              >
              <!-- <el-radio label="N" size="large">否</el-radio> -->
            </el-radio-group>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8"> -->
        <!-- <el-form-item label="所属模块" prop="module">
            <el-autocomplete
              v-model="ruleForm.module"
              :fetch-suggestions="formField"
              clearable
              class="inline-input w-50"
              placeholder="Please Input"
            >
              <template #default="{ item }">
                <div class="value">
                  <span class="link">{{ item.name }}</span
                  >{{ item.value }}
                </div>
              </template>
            </el-autocomplete>
          </el-form-item> -->
        <!-- </el-col> -->
      </el-row>
      <el-row gutter="20">
        <el-col :span="8">
          <el-form-item label="插件名" prop="pluginName">
            <!-- <el-autocomplete
              v-model="ruleForm.pluginName"
              :fetch-suggestions="formField"
              clearable
              class="inline-input w-50"
              placeholder="Please Input"
            >
              <template #default="{ item }">
                <div class="value">
                  <span class="link">{{ item.name }}</span
                  >{{ item.value }}
                </div>
              </template>
            </el-autocomplete> -->
            <el-input
              v-model="ruleForm.pluginName"
              placeholder="Please input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="包名" prop="packageName">
            <el-input
              v-model="ruleForm.packageName"
              placeholder="Please input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="模块名" prop="moduleName">
            <el-input
              v-model="ruleForm.moduleName"
              placeholder="Please input"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row gutter="20">
        <el-col :span="8">
          <el-form-item label="功能名" prop="functionName">
            <el-input
              v-model="ruleForm.functionName"
              placeholder="Please input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="业务名" prop="busName">
            <el-input v-model="ruleForm.busName" placeholder="Please input" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="类名" prop="className">
            <el-input v-model="ruleForm.className" placeholder="Please input" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row gutter="20">
        <el-col :span="8">
          <el-form-item label="作者" prop="authorName">
            <el-input
              v-model="ruleForm.authorName"
              placeholder="Please input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="排序">
            <el-input-number
              v-model="ruleForm.sortCode"
              :precision="0"
              :step="1"
              :min="0"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { Edit, Picture, UploadFilled } from "@element-plus/icons-vue";
import { ref, onMounted, reactive, watch,onUpdated } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import menu from "@/api/menu/menu.js";
import genBasic from "@/api/gen/genBasic";

const emit = defineEmits({ closed: null });
const stepActive = ref(1);
const tableData = ref();
const basicRef = ref();
const fullscreenLoading = ref(true)
const tableList = ref([]);
const formField = ref([
  { value: "id", name: "编号" },
  { value: "name", name: "名称" },
]);
const menuData = ref([]);
const generateTypeOptions = ref([
  {
    label: "压缩包",
    value: "ZIP",
  },
  {
    label: "项目内",
    value: "PRO",
  },
]);
const tablePrefixOptions = ref([
  {
    label: "移除",
    value: "Y",
  },
  {
    label: "不移除",
    value: "N",
  },
]);
const formLayoutOptions = ref([
  {
    label: "垂直",
    value: "vertical",
  },
  {
    label: "水平",
    value: "horizontal",
  },
]);
interface RuleForm {
  id: string;
  dbTable: string;
  dbTableKey: string;
  pluginName: string;
  moduleName: string;
  tablePrefix: string;
  generateType: string;
  module: string;
  menuPid: string;
  functionName: string;
  busName: string;
  className: string;
  formLayout: string;
  gridWhether: string;
  packageName: string;
  authorName: string;
  sortCode: string;
  mobileModule: string;
}
interface DbTableKey {
  columnName: string;
  typeName: string;
  columnRemark: string;
}
const defaultProps = {
  children: "children",
  label: "name",
};
const formSize = ref("default");
const dbTableKeyList = ref<DbTableKey[]>([]);
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  id: "",
  dbTable: "",
  dbTableKey: "",
  pluginName: "shop-service",
  moduleName: "biz",
  tablePrefix: tablePrefixOptions.value[0].value,
  generateType: generateTypeOptions.value[0].value,
  module: "",
  menuPid: "",
  functionName: "",
  busName: "",
  className: "",
  formLayout: "",
  gridWhether: "",
  packageName: "com.hpsk",
  authorName: "",
  sortCode: "99",
  mobileModule: "",
});

const rules = reactive<FormRules<RuleForm>>({
  dbTable: [{ required: true, message: "表不能为空", trigger: "blur" }],
  dbTableKey: [
    {
      required: true,
      message: "表主键不能为空",
      trigger: "change",
    },
  ],
  pluginName: [
    {
      required: true,
      message: "插件名不能为空",
      trigger: "blur",
    },
  ],
  packageName: [
    {
      required: true,
      message: "包名不能为空",
      trigger: "blur",
    },
  ],
  moduleName: [
    {
      required: true,
      message: "模块名不能为空",
      trigger: "blur",
    },
  ],
  functionName: [
    {
      required: true,
      message: "功能名不能为空",
      trigger: "blur",
    },
  ],
  busName: [
    {
      required: true,
      message: "业务名不能为空",
      trigger: "blur",
    },
  ],
  className: [
    {
      required: true,
      message: "类名不能为空",
      trigger: "change",
    },
  ],
  authorName: [
    {
      required: true,
      message: "作者不能为空",
      trigger: "blur",
    },
  ],
  module: [
    {
      required: true,
      message: "所属模块不能为空",
      trigger: "change",
    },
  ],
  menuPid: [
    {
      required: true,
      message: "上级目录不能为空",
      trigger: "change",
    },
  ],
});
interface Tree {
  id: number;
  label: string;
  children?: Tree[];
}

onMounted(() => {
//   genTableAll();
//   menu.getAllList().then((data) => {
//     menuData.value = data.data;
//   });
  fullscreenLoading.value =false
});
// onUpdated(()=>{
//     genTableAll();
//   menu.getAllList().then((data) => {
//     menuData.value = data.data;
//   });
//   fullscreenLoading.value =false
// })
watch(
  tableData,
  () => {
    ruleForm.dbTable = tableData.value;
    // ruleForm.functionName = "";
    dbTableKeyList.value = [];
    if (tableData.value) {
      const matchedItem = "";
      console.log("ruleForm",ruleForm)
      const tableNameChage = matchedItem ? matchedItem.tableName : "";
      console.log(tableNameChage);
      
      genBasic.tableColumns(ruleForm.dbTable).then((item) => {
        const checkTbKey = item.data.some(
          (i) => i.columnName === ruleForm.dbTableKey
        );
        if (!checkTbKey) {
          ruleForm.dbTableKey = "";
        }
        dbTableKeyList.value = item.data;
      });
    } else {
      ruleForm.dbTableKey = "";
    }
  },
  { deep: true }
);

const genTableAll = () => {
   genBasic.getAllTableInfo().then((item) => {
    console.log(item.data);
    
    tableList.value = {...item.data} 
  });
  console.log("genTableAll",tableList.value);
  
};
// 获取数据库表的驼峰命名
const getTableNameToHump = (tableName) => {
  if (tableName) {
    const arr = tableName.toLowerCase().split("_");
    if (ruleForm.tablePrefix === "Y") {
      arr.splice(0, 1);
    }
    for (let i = 0; i < arr.length; i++) {
      // charAt()方法得到第一个字母，slice()得到第二个字母以后的字符串
      arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1);
    }
    return arr.join("");
  }
  return "";
};
// 获取数据库表的驼峰命名
const getClassName = (tableName) => {
  if (tableName) {
    const arr = tableName.toLowerCase().split("_");
    for (let i = 0; i < arr.length; i++) {
      // charAt()方法得到第一个字母，slice()得到第二个字母以后的字符串
      arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1);
    }
    return arr.join("");
  }
  return "";
};
const goOnContinue = async (formEl: FormInstance | undefined) => {
  console.log("ruleForm", ruleForm);

  var stepValue = 0;
  if (stepActive.value === 1) {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
      if (valid) {
        stepValue = stepValue + 1;
        console.log("submit!");
        if(ruleForm.id){
            return
        }

        genBasic.add(ruleForm);
      } else {
        return;
      }
    });
  } else {
    stepValue = 1;
  }
  stepActive.value = stepActive.value + stepValue;
};
const configSteps = (record) => {
    genTableAll();
  menu.getAllList().then((data) => {
    menuData.value = data.data;
  });
  console.log("recordrecordrecord", record);
  if(record){
    genBasic.detail({ id: record.id }).then((item) => {
    const data = item.data;
    tableData.value = data.dbTable;
    ruleForm.id = data.id;
    ruleForm.dbTableKey = data.dbTableKey;
    ruleForm.menuPid = data.menuPid;
    ruleForm.generateType = data.generateType;
    ruleForm.className = getClassName(data.className);
    ruleForm.busName = data.busName;
    ruleForm.functionName = data.functionName;
    ruleForm.authorName = data.authorName;
    console.log("reeeeeeeeee",data);
    console.log("reeeeeeeeeeruleForm",ruleForm);
    
    // ruleForm = data;
  });
  }

};
// 抛出钩子
defineExpose({
  configSteps,
});
</script>

<style></style>
